package org.gruposp2p.proyectokarma.search;

import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

@Repository("searchHelper")
public class SearchHelper {

    private static Logger logger =
            LoggerFactory.getLogger(SearchHelper.class);

    // a Hibernate SessionFactory
    @Autowired private SessionFactory sessionFactory;

    @Transactional(readOnly = true)
    public <T> List<T> findByFullText(Class<T> entityClass,
            String[] entityFields, String textToFind, int firstResult, int maxResults) {
        FullTextSession session = Search.getFullTextSession(
                sessionFactory.getCurrentSession());
        MultiFieldQueryParser parser =
                new MultiFieldQueryParser(entityFields, new StandardAnalyzer());
        Query luceneQuery;
        try {
            luceneQuery = parser.parse(textToFind);
        } catch (ParseException e) {
            logger.error("Cannot parse [" + textToFind + "] to a full text query", e);
            return new ArrayList<T>(0);
        }
        FullTextQuery query = session.createFullTextQuery( luceneQuery, entityClass );
        return query.setFirstResult(firstResult).setMaxResults(maxResults).list();
    }

    
}
